package net.starwifi.duobao.web;


import net.starwifi.duobao.entity.Member;
import net.starwifi.duobao.mvc.Message;
import net.starwifi.duobao.service.MemberService;
import net.starwifi.duobao.service.RSAService;
import net.starwifi.duobao.service.SmsLogService;
import net.starwifi.duobao.utils.StringUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Controller - 共用
 * 
 * @author ruoo
 * @version 1.0
 */
@Controller("wapCommonController")
public class CommonController {

	@Autowired
	private RSAService rsaService;

	@Autowired
	private SmsLogService smsLogService;




	/**
	 * 新手指南
	 */
	@RequestMapping(value = "/user_guide", method = RequestMethod.GET)
	public  String user_guide(HttpServletRequest request) {
		return "common/user_guide";
	}


	/**
	 * 聚宝盆
	 */
	@RequestMapping(value = "/jbp", method = RequestMethod.GET)
	public  String jbp(HttpServletRequest request) {
		return "common/jbp";
	}



	/**
	 * 下载
	 */
	@RequestMapping(value = "/download", method = RequestMethod.GET)
	public  String apkDownload(HttpServletRequest request) {
		return "common/download";
	}




	/**
	 * 公钥
	 */
	@RequestMapping(value = "/public_key", method = RequestMethod.GET)
	public @ResponseBody Object publicKey(HttpServletRequest request) {
		final RSAPublicKey publicKey = rsaService.generateKey(request);
		return Message.createMessage(Message.success("success"), new HashMap<String, Object>(){{
			put("modulus", Base64.encodeBase64String(publicKey.getModulus().toByteArray()));
			put("exponent", Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray()));

		}});
	}

	/** 手机号码合法性*/
	public static boolean isMobileNO(String mobiles){
		Pattern p = Pattern.compile("^((133|153|180|181|189|177))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}


	/**
	 * 获取短信验证码.
	 * @param phone 手机号码
	 * @param type 类型
	 */
	@RequestMapping(value = "/get_sms_code", method = RequestMethod.GET)
	public @ResponseBody Object getSmsCode(String phone,String type,HttpServletRequest request) {
		String key="sms_"+type+"_"+phone;
		Map<String,String> map=new HashMap<String, String>();
		String code=StringUtils.getRandomNumber(6);
		map.put("{code}", code);
		HttpSession session = request.getSession();
		session.setAttribute(key, code);
		return smsLogService.sendSms(type, phone, map);
	}




	/**
	 * 校验短信验证码.
	 * @param phone 手机号码
	 * @param type 类型
	 */
	@RequestMapping(value = "/validate_sms_code", method = RequestMethod.GET)
	public @ResponseBody Object validateSmsCode(String phone,String code,String type,HttpServletRequest request) {
		String key="sms_"+type+"_"+phone;
		if(request.getSession().getAttribute(key)==null){
			return Message.error("验证码错误");
		}
		String sessionCode=(String)request.getSession().getAttribute(key);
		if(!sessionCode.equals(code)){
			return Message.error("验证码错误");
		}
		final String uuid=StringUtils.getUUID();
		request.getSession().setAttribute("sms_" + type + "_" + phone + "_" + "success", uuid);
		return Message.success(uuid);
	}


	/**
	 * 校验短信验证码.
	 * @param phone 手机号码
	 */
	@RequestMapping(value = "/setPass")
	public @ResponseBody Object setPass(String phone,String uuid,HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		String uuidKey="sms_findPass_"+phone+"_"+"success";
		if(request.getSession().getAttribute(uuidKey)==null){
			return Message.error("无验证授权");
		}
		String sessionCode=(String)request.getSession().getAttribute(uuidKey);
		if(!sessionCode.equals(uuid)){
			return Message.error("无验证授权");
		}
		String password = rsaService.decryptParameter("pass", request);
		Member member=memberService.findByMobile(phone);
		if(member==null){
			return Message.error("用户不存在");
		}
		String salt= net.starwifi.duobao.utils.StringUtils.getUUID();
		member.setSalt(salt);
		member.setPassword(DigestUtils.md5Hex(password + salt));
		memberService.update(member);
		return Message.success("密码修改成功");
	}

	@Autowired
	MemberService memberService;

	/**
	 * 错误提示
	 */
	@RequestMapping("/error")
	public String error() {
		return "/common/error";
	}

	/**
	 * 资源不存在
	 */
	@RequestMapping("/resource_not_found")
	public String resourceNotFound(HttpServletRequest request) {

		return "/common/resource_not_found";
	}

	/**
	 * 资源不存在
	 */
	@RequestMapping("/401")
	public String unAuth(HttpServletRequest request) {

		return "/common/401";
	}

	/**
	 * 资源不存在
	 */
	@RequestMapping("/403")
	public String unAuth3(HttpServletRequest request) {

		return "/common/403";
	}


	/**
	 * 版本更新日志
	 */
	@RequestMapping("/changelog")
	public String changelog(HttpServletRequest request) {
		return "/common/change_log";
	}


	/**
	 * 版本更新日志
	 */
	@RequestMapping("/about")
	public String about(HttpServletRequest request) {
		return "/common/about";
	}



	/**
	 * 获取地理坐标
	 */
	@RequestMapping(value = "/getMap")
	public String  getMap(String tag,String lng,String lat,Model model) {
		if(tag!=null){
			model.addAttribute("tag",tag);
		}
		if(lng!=null){
			model.addAttribute("lng",lng);
		}
		if(lat!=null){
			model.addAttribute("lat",lat);
		}
		return "/common/get_map";
	}

}